const mongoose = require("mongoose");
const usersModel = mongoose.model("users");
const { md5, secretKey } = require("../util/salt");
const jwt = require("jsonwebtoken");

const get = async ({ page, limit }) => {
    limit = ~~limit;
    const result = {};
    result.total = await usersModel.countDocuments();
    result.rows = await usersModel.find().skip((page - 1) * limit).limit(limit).sort({ _id: -1 }).exec();
    // result.rows = await usersModel.find().skip((page - 1) * limit).limit(limit).exec();
    return result;
}
const getOne = async _id => await usersModel.findOne({ _id });
const updata = async (conditions, doc) => {
    return await usersModel.updateOne(conditions, doc)
}

const add = async (user) => {
    return await usersModel.create(user)
}

const del = async (_id) => {
    return await usersModel.deleteOne({ _id });
}

const login = async ({ userName, userPassword }) => {

    const user = await usersModel.findOne({ userName, userPassword: md5(userPassword) });
    const data = {};

    if (user) {
        data._id = user._id;
        const payload = {
            name: user.userName
        };
        data.token = jwt.sign(payload, secretKey, {
            expiresIn: 60 * 60 * 24, // 秒
        });
        return data;
    }
};

const reg = async ({ userName, userPassword }) => {
    let data = await usersModel.findOne({ userName });
    data = !data ? await usersModel.create({ userName, userPassword: md5(userPassword) }) : false;
    return data;
}

module.exports = {
    get,
    getOne,
    updata,
    add,
    del,
    login,
    reg
}